import os
import csv
import json


def save_metrics(metrics, csv_path):
    fieldnames = list(metrics.keys())
    write_header = not os.path.exists(csv_path)  # 如果文件不存在，就写表头

    with open(csv_path, "a", newline="") as f:  # newline="" 避免多余空行
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        if write_header:
            writer.writeheader()
        writer.writerow(metrics)

def save_hyperparameters(args, config, output_dir, pipeline, best_params=None):
    # 公共参数
    common_params = {
        "Model": args.model,
        "Seed": args.seed,
        "Experiment": args.experiment,
    }

    if pipeline == "ml":
        # ML 传统模型参数
        ml_params = {
            "Search Type": config.SEARCH_TYPE,
            "CV Folds": config.CV_FOLDS,
            "N Iter": config.N_ITER,
            "Scoring": config.SCORING_CLASSIFICATION if args.experiment == 'classification' else config.SCORING_REGRESSION,
            "N Jobs": config.N_JOBS,
            "Params": best_params if best_params else None
        }
    elif pipeline == "dl":
        # DL 模型参数
        dl_params = {
            "Batch Size": config.BATCH_SIZE,
            "Learning Rate": config.LEARNING_RATE,
            "Epochs": config.EPOCHS,
            "Dropout": config.DROPOUT,
            "Embedding Dim": config.EMBEDDING_DIM,
            "Hidden Dim": config.HIDDEN_DIM,
        }

    # 各模型专属参数
    model_specific = {}
    if args.model == "transformer":
        model_specific.update({
            "Heads": config.HEADS,
            "Depth": config.DEPTH,
            "Attn Dropout": config.ATTN_DROPOUT,
        })
    elif args.model == "mlp":
        model_specific.update({
            "Hidden Dims": config.HIDDEN_DIMS_MLP,
        })
    elif args.model == "lstm":
        model_specific.update({
            "Num Layers": config.NUM_LAYERS,
            "Bidirectional": config.BIDIRECTIONAL,
        })

    # 汇总
    if pipeline == "ml":
        all_params = {
            "common": common_params,
            "ml": ml_params,
            "model_specific": model_specific
        }

    elif pipeline == "dl":
        all_params = {
            "common": common_params,
            "dl": dl_params,
            "model_specific": model_specific
        }

    # 保存 JSON
    with open(os.path.join(output_dir, "hyperparameters.json"), "w") as f:
        json.dump(all_params, f, indent=4)
